<template>
    <div class="login-box " v-title data-title="登录页面">
        <!-- 通过:rules="loginFormRules"来绑定输入内容的校验规则 -->
        <el-form :rules="loginFormRules" ref="loginForm" :model="loginForm" label-position="right" label-width="auto"
                 show-message>
            <span class="login-title">欢迎登录</span>
            <div style="margin-top: 5px"></div>
            <el-form-item label="用户名" prop="username">
                <el-col :span="22">
                    <el-input type="text" v-model="loginForm.username"></el-input>
                </el-col>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-col :span="22">
                    <el-input @keyup.native.enter="loginSubmit('loginForm')" type="password"
                              v-model="loginForm.password"></el-input>
                </el-col>
            </el-form-item>
            <el-form-item>
                <div id="userType">
                    <el-select v-model="value" placeholder="请选择登录类型">
                        <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </div>
                <el-button type="primary" @click="loginSubmit('loginForm')">登录</el-button>
                <el-button type="primary" @click="dialogVisible=true">注册</el-button>
                <el-button type="primary" @click="visit">游客登录</el-button>


            </el-form-item>
        </el-form>


        <el-dialog title="注册" :visible.sync="dialogVisible" width="60%">
            <el-form :rules="registFormRules" ref="registForm" :model="registForm" label-width="80px">
                <el-form-item prop="r_username" label="用户名">
                    <el-input type="text" v-model="registForm.r_username" autocomplete="off"></el-input>
                </el-form-item>

                <el-form-item prop="r_passwordFir" label="密码">
                    <el-input type="password" v-model="registForm.r_passwordFir"/>
                </el-form-item>

                <el-form-item prop="r_passwordSec" label="确认密码">
                    <el-input type="password" v-model="registForm.r_passwordSec"/>
                </el-form-item>

                <el-form-item prop="r_email" label="邮箱">
                    <el-input type="text" v-model="registForm.r_email"/>
                </el-form-item>

                <el-form-item prop="r_verifycode" label="验证码">
                    <el-input type="text" v-model="registForm.r_verifycode"/>
                    <el-button :disabled="disabled" style="margin-top:10px" @click="verifyEmail" :type="verifyBtnType">
                        {{verifyBtnState}}
                    </el-button>
                    <div v-if="verifyBtnState == '正在发送...'">
                        {{sendCodeCountDown}}秒后可重新发送
                    </div>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="registSubmit('registForm')">确 定</el-button>
      </span>
        </el-dialog>
    </div>
</template>
<script>
    import main from "/src/main.js"

    export default {
        name: "login",
        data() {
            let _this = this;
            const validateUser = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('用户名不可为空'))
                } else {
                    //查询该用户名是否已经存在
                    axios.get(main.requestAddress + '/user/findUserByUsername', {
                        params: {'username': value}
                    }).then(function (response) {
                        let flag = response.data.data
                        if (flag == true) {
                            callback(new Error('该用户名太出名了，请您换一个吧'))
                        } else {
                            callback();
                        }
                    }).catch(function (error) {
                        alert(error);
                    });
                }
            };
            const validateEmail = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入邮箱'));
                } else {
                    let regExp = /^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/;
                    let emailIsValid = regExp.test(value)
                    if (!emailIsValid) {
                        callback(new Error('您的邮箱输入有误，请重新输入！'));
                    } else {
                        axios.get(main.requestAddress + '/user/findUserByEmail', {
                            params: {'email': value}
                        }).then(function (response) {
                            if (response.data.data === true) {
                                _this.$message.error('您好，该邮箱已被注册，请换一个吧！');
                                _this.$data.disabled = true
                            } else {
                                callback();
                                _this.$data.disabled = false
                                _this.$data.verifyBtnType = 'success'
                            }
                        }).catch(function (error) {
                            alert(error);
                        });
                    }
                    callback();
                }
            };
            const validateSec = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.registForm.r_passwordFir) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            return {
                options: [
                    {
                      value: 'user',
                      label: 'user'
                    },
                    {
                        value: 'admin',
                        label: 'admin'
                    }
                ],
                value: 'user',
                bodyBackgroundImage: 'url(' + require('../assets/img/back.jpg') + ')',
                sendCodeCountDown: 60,
                disabled: false,
                verifyBtnState: '获取验证码',
                verifyBtnType: 'info',
                dialogVisible: false,
                registForm: {
                    r_username: '',
                    r_passwordFir: '',
                    r_passwordSec: '',
                    r_email: '',
                    r_verifycode: ''
                },
                registFormRules: {
                    r_username: [
                        {
                            required: true,
                            validator: validateUser,
                            trigger: 'blur'
                        },
                        {
                            min: 5,
                            max: 15,
                            message: '长度在 5 到 15 个字符',
                            trigger: 'blur'
                        }],
                    r_passwordFir: [{
                        required: true,
                        message: '密码不可为空',
                        trigger: 'blur'
                    }],
                    r_passwordSec: [{
                        required: true,
                        validator: validateSec,
                        trigger: 'blur'
                    }],
                    r_email: [{
                        required: true,
                        validator: validateEmail,
                        trigger: 'blur'
                    }],
                    r_verifycode: [{
                        required: true,
                        message: '请输入验证码',
                        trigger: 'click'
                    }]
                },
                loginForm: {
                    username: '',
                    password: ''
                },
                // 表单验证，需要在 el-form-item 元素中增加 prop 属性
                loginFormRules: {
                    username: [
                        {required: true, message: '账号不可为空', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '密码不可为空', trigger: 'blur'}
                    ]
                },
                message: ''
            }
        },
        mounted() {
            this.setBackgroundImg();
        },
        beforeDestroy() {
            this.delBackgroundImg();
        },
        methods: {
            setBackgroundImg() {
                document.body.style.backgroundImage = this.bodyBackgroundImage
            },
            delBackgroundImg() {
                document.body.style.backgroundImage = "";
            },
            visit() {
                sessionStorage.setItem("token", true);
                // console.log()
                sessionStorage.setItem("username", "visitor");
                this.$router.push("/index");
            },
            verifyEmail() {
                let _this = this
                if (this.$data.registForm.r_email === '') {
                    this.$message.error('您好，请输入邮箱！');
                    return;
                } else {
                    this.$data.verifyBtnState = '正在发送...'
                    this.$data.disabled = true

                    //高效定时器
                    let i = setInterval(function () {
                        _this.$data.sendCodeCountDown--;
                        if (_this.$data.sendCodeCountDown == 0) {
                            _this.$data.verifyBtnState = '获取验证码'
                            _this.$data.disabled = false
                            clearInterval(i);
                        }

                    }, 1000)
                    this.$data.sendCodeCountDown = 60

                    //获取验证码
                    axios.get(main.requestAddress + '/user/getCode', {
                        params: {
                            'email': this.$data.registForm.r_email,
                            'username': this.$data.registForm.r_username
                        }
                    }).then(function (response) {
                        _this.$message.success(response.data.message)
                    }).catch(function (error) {
                        alert(error);
                    });

                }
            },
            openLoginFailMessage() {
                this.$alert(this.$data.message, '温馨提示', {
                    confirmButtonText: '确定',
                    callback: action => {
                    }
                });
            },
            registSubmit(formName) {
                let _this = this
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.$axios.post(main.requestAddress + `/user/regist`, _this.registForm)
                            .then(response => {
                                let flag = response.data.data
                                if (flag == true) {
                                    _this.$message.success(response.data.message)
                                    _this.$data.dialogVisible = false;
                                } else {
                                    _this.$message.error(response.data.message)
                                    _this.$data.disabled = true
                                }
                            })
                            .catch(Error => {
                                console.log(Error)
                            })

                    } else {
                        return false;
                    }
                });
            },
            loginSubmit(formName) {
                let _this = this
                // 为表单绑定验证功能
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let userType = _this.value
                        if(userType === 'user'){
                            // 使用 vue-router 路由到指定页面，该方式称之为编程式导航
                            this.$axios.post(main.requestAddress + `/user/login`, _this.loginForm)
                                .then(res => {
                                    _this.$data.message = res.data.message
                                    //若数据库查询失败 则返回重新登录信息
                                    if (res.data.data === null) {
                                        _this.openLoginFailMessage();
                                        return;
                                    }
                                    sessionStorage.setItem("token", true);
                                    // console.log()
                                    sessionStorage.setItem("username", res.data.data.username);
                                    _this.$router.push("/index");
                                })
                                .catch(Error => {
                                    console.log(Error)
                                })
                        }else if(userType === 'admin'){
                            this.$axios.post(main.requestAddress + `/admin/login`, _this.loginForm)
                                .then(res => {
                                    _this.$data.message = res.data.message
                                    //若数据库查询失败 则返回重新登录信息
                                    if (res.data.data === null) {
                                        _this.openLoginFailMessage();
                                        return;
                                    }
                                    sessionStorage.setItem("token", true);
                                    sessionStorage.setItem("username", res.data.data.username);
                                    _this.$router.push("/index");
                                })
                                .catch(Error => {
                                    console.log(Error)
                                })
                        }
                    } else {
                        return false;
                    }
                });
            }
        }
    }
</script>

<style>
    #userType{
        margin-bottom: 10px;
        margin-top: -5px;
    }

    body {
        background-size: cover;
    }

    .login-box {
        border: 1px solid #DCDFE6;
        width: 350px;
        margin: 180px auto;
        padding: 35px 35px 15px 35px;
        border-radius: 5px;
        -webkit-border-radius: 5px;
        -moz-border-radius: 5px;
        box-shadow: 0 0 25px palegreen;
    }

    .login-title {
        text-align: center;
        margin: 0 auto 40px auto;
        color: #66CD00;
        font-size: 30px;
        font-weight: bold;
    }
</style>